package Agent;

import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.sql.SQLException;
import java.util.ArrayList;

import Exception.ExceptionFreeAgent;
import Exception.ExceptionVM;
import MachineLearning.LinearRegression;
import SLA.SLA;

public class ImplemAgent extends UnicastRemoteObject implements Agent{
	

	//dados do agente
	private String ip;
	private String agentName;
	private int port;
	private static int countThreads;
	
			
	//agente esta executando uma carga
	private boolean on;
	
	protected ImplemAgent(String ip, String agentName, int port) throws ClassNotFoundException, SQLException, IOException {
		super();
		this.ip = ip;
		this.agentName = agentName;
		this.port = port;
		
		on = false;
		
		//o agente se registra
		Registry registry = LocateRegistry.createRegistry(port);
        registry.rebind(agentName, this);
        System.out.println(agentName+" Registrado!");     
	}
	

	@Override
	public void query(ArrayList<String> array, SLA sla, LinearRegression machine) throws RemoteException, ClassNotFoundException, SQLException,InterruptedException, ExceptionVM, ExceptionFreeAgent{
		countThreads++;
		
		on = true;
		ThreadAgent t = new ThreadAgent(agentName,array, sla, machine);
	    t.start();
	    
	    t.join();
	    
	    countThreads--;
	    
	    if(!t.getTransaction().isEmpty()){
	    	double totalTime = t.getSLA().getSelectivityQ()/sla.getSloValue();
	    	totalTime -= (t.getTimeQueriesAlreadyExecuted()+t.getTimeMonitoring());
	    	int count = (int) (totalTime*sla.getSloValue());
	    	
	    	if(count>0) throw new ExceptionVM(t.getTransaction(), count);
	    	else{
	    		throw new ExceptionFreeAgent(t.getTransaction());
	    	}
	    }
	}

	@Override
	public boolean isOn() throws RemoteException {
		return on;
	}


	@Override
	public void setOn(boolean on) throws RemoteException {
		this.on=on;
		
	}	
	
	public static void main(String[] args) throws NumberFormatException, ClassNotFoundException, SQLException, IOException {
		ImplemAgent agent = new ImplemAgent(args[0],args[1],Integer.parseInt(args[2]));
	}


	
}
